import sys, pygame, unittest
from enemy import Enemy
from snake import Level

pygame.init()

#Todo: implement this
def detectSpawn(map, color):
    r = pygame.Rect(10,10,10,10)
    return r

#Todo: implement this
def detectHome(map, color):
    r = pygame.Rect(10,10,10,10)
    return r

#Todo: Flush out this function to be useful
def detectPath(map, color):
    path = []
    for x in range(map.get_width()):
        for y in range(map.get_height()):
            if map.get_at((x,y)) == color:
                path.append((x,y))
    return path

#Todo: don't do this if it is on the path   
def createTower(map, position):
    r = tower.get_rect()
    map.blit(tower, r.move(position))

#Todo: Game loop rules need to be better defined than this : )
def gameLoop(map,enemies,path, spawn, home):
    size = width,height = map.get_width(), map.get_height()
    screen = pygame.display.set_mode(size)

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                createTower(map, event.pos)

        screen.blit(map,map.get_rect())

        for enemy in enemies:
            screen.blit(enemy, enemy.rect)
            enemy.rect = pygame.Rect(path[enemy.pos], (enemy.size))
            enemy.pos = enemy.pos + 1
            if enemy.pos >= len(path):
                enemies.remove(enemy)

        pygame.display.flip()

        if len(enemies) == 0:
            sys.exit()


#Todo: Read these constrains into map class
level = Level()

map = pygame.image.load(level.mapName)
tower = pygame.image.load(level.towerName)
path = detectPath(map, level.pathColor)
spawn = detectSpawn(map, level.spawnColor)
home = detectHome(map, level.homeColor)

enemies = []
for i in range(level.enemyCount):
    enemies.append(Enemy())

gameLoop(map, enemies, path, spawn, home)
